package com.ruoyi.personal.ws;




import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/ws/data/{username}")
@Component
@Slf4j
public class DateEndpoint {
    private static Map<String, Session> sessions = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessions.put(username.trim(), session);
        log.info("Current sessions after adding: " + sessions.keySet());
        //sendMessageToUser(username,"恭喜"+ username + "连接成功");
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        sessions.remove(username);
        log.info("onClose: " + username);
    }


    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        log.info("onMessage: " + username + " - Message: " + message);
//        String responseMessage = "Hello, " + username + "! You sent: " + message;
//        sendMessageToUser(username, responseMessage);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.info("onError: " + error.getMessage());
    }

    /*根据名字，和 message  发送*/
    public void sendMessageToUser(String username, String message) {
        log.info("Current sessions: " + sessions.keySet());
        Session session = sessions.get(username);
        if (session != null) {
            sendMessage(session, message);
        } else {
            log.warn("Session not found for user: " + username);
        }
    }

    private void sendMessage(Session session, String message) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("Error sending message: " + e.getMessage());
        }
    }


}

